﻿using System.Collections.ObjectModel;

namespace System.Windows.Markup
{
	/// <summary>
	/// A simple markup extension to return an array of the specified type.
	/// </summary>
	[ContentProperty("Items")]
	public sealed class ArrayExtension : MarkupExtension
	{
		#region Private Variables 
		private readonly Collection<object> _items = new Collection<object>();
		#endregion Private Variables 

		#region Public Properties 
		/// <summary>
		/// Gets the collection of items that should comprise the array.
		/// </summary>
		public Collection<object> Items
		{
			get
			{
				return this._items;
			}
		}

		/// <summary>
		/// Gets the element type of the array.
		/// </summary>
		public Type ItemType
		{
			get;
			set;
		}
		#endregion Public Properties 

		#region Public Methods 
		/// <summary>
		/// When implemented in a derived class, returns an object that is provided as the value of the target property for this markup extension.
		/// </summary>
		/// <param name="serviceProvider">A service provider helper that can provide services for the markup extension.</param>
		/// <returns>The object value to set on the property where the extension is applied.</returns>
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			if (this.ItemType == null || this.ItemType.IsGenericTypeDefinition)
			{
				throw new InvalidOperationException("ItemType must be specified and not a generic type definition.");
			}
			Array array = Array.CreateInstance(this.ItemType, this.Items.Count);
			for (int index = 0; index < array.Length; index++)
			{
				array.SetValue(this.Items[index], index);
			}
			return array;
		}
		#endregion Public Methods 
	}
}